package com.szholly.plug.form.directive;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Component;

import com.szholly.utils.freemarker.directive.DirectiveUtils;
import com.szholly.utils.freemarker.directive.IDirective;
import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.utils.spring.springmvc.route.FunctionInfo;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.common.util.TreeDataUtils;
import com.szholly.data.general.IQueryMap;
import com.szholly.data.general.ITable;
import com.szholly.data.general.ITableFactory;
import com.szholly.data.general.QueryMap;
import com.szholly.data.general.RowBase;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 定义Combox下拉框的字典的json数据自定义标签
 */
@Component("directive_treedomain")
public class TreeDomainDirective implements TemplateDirectiveModel, IDirective {
	/**
	 * 定义字典表名称
	 */
	private static String PARA_TABLENAME = "tableName";
	/**
	 * 定义排序条件
	 */
	private static String PARA_ORDER = "order";
	/**
	 * 定义数据查询的级别
	 */
	private static String PARA_JBS = "jbs";
	/**
	 * 是否添加空行
	 */
	private static String PARA_ADDSPACEITEM = "addSpaceItem";

	@Override
	public FunctionInfo getFunctionInfo() {
		String paraInfo = "";

		FunctionInfo info = new FunctionInfo("treedata", 1, "表单",
				"获取树型下拉框的字典数据", paraInfo);
		return info;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void execute(Environment env, Map params, TemplateModel[] model,
			TemplateDirectiveBody body) throws TemplateException, IOException {

		String tableName = DirectiveUtils.getString(PARA_TABLENAME, params);
		String order = DirectiveUtils.getString(PARA_ORDER, params);
		String jbs = DirectiveUtils.getString(PARA_JBS, params);
		Boolean addSpaceItem = DirectiveUtils.getBool(PARA_ADDSPACEITEM, params);
		
		if (StringUtils.IsNullOrSpace(tableName)) {
			return;
		}

		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory
				.getBean("TableFactory");
		ITable pTable = tableFactory.openTable(tableName);
		IQueryMap queryMap = new QueryMap();
		queryMap.setAddCaptionField(true);
		queryMap.getOrderByMap().put(order, 1);

		List<Map<String, Object>> result = null;
		// 没条件时，加上只加载指定级别数据
		if (!StringUtils.IsNullOrSpace(pTable.getLevelFieldName())
				&& !StringUtils.IsNullOrSpace(jbs)) {
			queryMap.getWhereMap().put(pTable.getLevelFieldName() + ":in", jbs);
		}
		List<RowBase> rows = pTable.getEntityList(RowBase.class, queryMap);
		result = TreeDataUtils.GetTreeData(rows, pTable.getIDFieldName(),
				pTable.getPIDFieldName(), pTable.getIsChildFieldName(),
				pTable.getCodeFieldName(), pTable.getCaptionFieldName());
		if (addSpaceItem != null && addSpaceItem == true) {
			Map<String, Object> spaceNode = new HashMap<String, Object>();
			spaceNode.put(pTable.getIDFieldName(), "");
			spaceNode.put(pTable.getPIDFieldName(), "");
			spaceNode.put(pTable.getIsChildFieldName(), "1");
			spaceNode.put(pTable.getCodeFieldName(), "");
			spaceNode.put(pTable.getCaptionFieldName(), "");
			if (result == null) {
				result = new ArrayList<Map<String, Object>>();
			}
			result.add(0, spaceNode);
		}
		
		JSONArray arrayObject = JSONArray.fromObject(result);
		String returnValue = arrayObject.toString();
		
		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		paramWrap.put("data", DEFAULT_WRAPPER.wrap(returnValue));
		Map<String, TemplateModel> origMap = DirectiveUtils
				.addParamsToVariable(env, paramWrap);
		body.render(env.getOut());
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}
}